<template>
  <div>
    <el-button
      size="small"
      :loading="loading"
      v-bind="$attrs"
      :disabled="state.count > 0 ? true : $attrs.disabled"
      @click="onClick"
    >
      <slot></slot>
      <span v-if="state.count > 0">({{ state.count }})</span>
    </el-button>
  </div>
</template>
<script setup>
const emits = defineEmits(['click'])

const props = defineProps({
  throttle: {
    type: Number,
    default: 500
  },
  countDown: {
    type: Number,
    default: 5
  }
})

const loading = ref(false)
const state = reactive({
  count: props.countDown
})
let timer = null
const onClick = async e => {
  if (!props.throttle) {
    emits('click', e)
    return false
  }
  if (timer) {
    clearTimeout(timer)
  }
  emits('click', e)
  if (loading.value === false) {
    loading.value = true
  }
  timer = setTimeout(() => {
    loading.value = false
  }, props.throttle)
}

const countDownContrl = () => {
  timer = setInterval(() => {
    if (state.count > 0) {
      state.count--
    } else {
      clearInterval(timer)
    }
  }, 1000)
}
onMounted(() => {
  countDownContrl() && props.countDown > 0
})
</script>
<style lang="scss" scoped></style>
